<template>
  <div class="pagination">
    <button :disabled="currentPage===1" @click="$emit('changeNum',currentPage-1)">上一页</button>
    <button v-if="startEnd.start>1"  @click="$emit('changeNum',1)">1</button>
    <button v-if="startEnd.start>2" >···</button>
<!--v-for和v-if同时使用 v-for的优先级比v-if高-->
    <button :class="{active:page===currentPage}" v-for="page in startEnd.end" :key="page" v-if="page>=startEnd.start" @click="$emit('changeNum',page)">{{page}}</button>
    <button v-if="startEnd.end<totalPageNo-1">···</button>
    <button v-if="startEnd.end<totalPageNo" @click="$emit('changeNum',totalPageNo)">{{totalPageNo}}</button>
    <button :disabled="currentPage===totalPageNo" @click="$emit('changeNum',totalPageNo+1)">下一页</button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>
<!--<Pagination :currentPage="searchParams.pageNo" :total="searchListInfo.total" :pageSize="searchParams.pageSize" :currentNum="5"></Pagination>-->
<script>
export default {
  name: "Pagination",
  //接收数据 props接收的数据和computed和data中的数据都是vm可以访问的 直接用this.用
  props:{
    currentPage:{
      type:Number,
      required:true
    },
    total:{
      type:Number,
      default:0
    },
    pageSize:{
      type:Number,
      require:true
    },
    continueNum:{
      type:Number,
      default: 5
    }
  },
  computed:{
    //总页码
    totalPageNo(){
      return Math.ceil(this.total/this.pageSize)
    },
    //根据当前页得不同计算连续数的起始位置
    startEnd(){
      let {totalPageNo,continueNum,currentPage}=this
      // eslint-disable-next-line no-unused-vars
      let start=0
      // eslint-disable-next-line no-unused-vars
      let end=0
      //如果连续页大于总页数
      if (continueNum>totalPageNo){
        start=1,
        end=totalPageNo
      }else {
        //如果是正常的
        start=currentPage-Math.floor(continueNum/2)
        end=currentPage+Math.floor(continueNum/2)
        //向左修正
        if (start<1){
          start=1
          end=continueNum
        }
        //向右修正
        if (end>totalPageNo){
          end=totalPageNo
          start=totalPageNo-continueNum+1
        }
      }
      return {
        start,
        end
      }
    }
  }
}
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>

